SZJX

SZJX

Trying to get Typescript to work with Phoenix 1.4.0 dev

I’m now trying to start a new project with Phoenix 1.4.0 as it comes with Webpack by default, and I’m trying to get Typescript to work with it, which is surprisingly difficult.

I changed the file app.js to app.ts, and the problem I’m struggling with now is the first statement: import css from '../css/app.css';. Apparently, from questions such as https://stackoverflow.com/questions/41336858/how-to-import-css-modules-with-typescript-react-and-webpack, and https://stackoverflow.com/questions/40382842/cant-import-css-scss-modules-typescript-says-cannot-find-module, it’s a nontrivial task to import CSS modules in Typescript… Typescript wouldn’t recognize the module which doesn’t end in .js or .ts.

According to the instructions in that post, I tried to create a file called typings.d.ts:

declare module '*.css' {
  interface IClassNames {
    [className: string]: string;
  }
  const classNames: IClassNames;
  export = classNames;
}

Now, Typescript doesn’t complain about the module. However, running npx webpack --mode development doesn’t actually emit the CSS file whatsoever. webpack just completely ignores the app.css file.

The following is my webpack.config.js. I only changed two places:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = (env, options) => ({
  optimization: {
    minimizer: [new UglifyJsPlugin({ cache: true, parallel: true, sourceMap: false }), new OptimizeCSSAssetsPlugin({})]
  },
  // entry: './js/app.js',
  entry: './js/app.ts',
  output: {
    filename: 'app.js',
    path: path.resolve(__dirname, '../priv/static/js')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: 'ts-loader'
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader']
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({ filename: '../css/app.css' }),
    new CopyWebpackPlugin([{ from: 'static/', to: '../' }])
  ]
});

I think this should be fairly easy to replicate with a new project.

  • cd assets
  • npm install --save-dev typescript ts-loader
  • npx tsc init
  • Create typings.d.ts in the folder
  • Edit webpack.config.js

I think the problem might lie with the Typescript module declaration. Unfortunately I don’t know enough to come up with a more sensible solution. I tried to generate a module for each css file in the /css folder with GitHub - Quramy/typed-css-modules: Creates .d.ts files from CSS Modules .css files · GitHub, but Typescript complains that assets/css/app.css.d.ts' is not a module.

Should I just give up the idea of turning app.js into a Typescript file and try to integrate Typescript in some other fashion, e.g. wrapping it in a module which is to be imported in app.js?

Marked As Solved

SZJX

SZJX

Sorry, misread your reply in a hurry. I think the contents conform to the guides as well:

{
  "compilerOptions": {
    "target":      "es5",
    "module":      "commonjs",
    "strict": true, 
    "esModuleInterop": true
  }
}

It seems that importing CSS modules is inherently thorny with Typescript… The two workarounds that worked:

  • Keep app.js in Javascript. Then when importing other modules defined in TS, one needs to append the .ts suffix to those modules.
  • Use Typescript for app.ts but write
    declare function require(name: string): string;
    const css = require('../css/app.css');
    
    instead of import css from '../css/app.css'; at the top of app.ts.

Also Liked

peerreynders

peerreynders

FYI: The POI documentation recommends this tsconfig.json:

{
  "compilerOptions": {
    // this aligns with Vue's browser support
    "target": "es5",
    // this enables stricter inference for data properties on `this`
    "strict": true,
    // if using webpack 2+ or rollup, to leverage tree shaking:
    "module": "es2015",
    "moduleResolution": "node"
  }
}

Furthermore in Zero config React + Typescript + CSS Modules + JEST with Poi (2018-02-18):

Let’s get that fixed too and add a global.d.ts file with the following line in it:
declare module '*.css';

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New

Other popular topics Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement